<!--
 * @Author: 冯尚新 fengshangxin@yunjinhz.com
 * @Date: 2023-05-23 10:51:56
 * @LastEditors: 冯尚新 fengshangxin@yunjinhz.com
 * @LastEditTime: 2023-05-30 20:55:49
 * @FilePath: \zmglpt-ui-mobile-v1.1\dev\pages\case\official\docZmSampling.vue
 * @Description: 案件-专卖卷烟鉴别检验抽样单
-->
<template>
	<view class="page">
		<!-- #ifdef H5-ONLY -->
		<theme-navbar :is-white="false" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
			<view class="white-color" @click="printOrDown(state.canEdit)">
				{{ state.canEdit ? '预览' : '打印' }}
			</view>
		</theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="state.canEdit?fContent:fContents" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <view class="main-content">
      <view style="width: calc(100% + 30px);">
        <form-section title="卷烟鉴别检验抽样单"></form-section>
      </view>
      <u-form :model="zmSamplingForm" :error-type="errorType" :rules="rules" class="form-content" ref="uForm">
        <!-- <u-form-item label="文书编号" :label-position="labelPosition" prop="fullDocNo">
          <u-input
            placeholder="请输入文书编号"
            :disabled="!state.canEdit"
            v-model="zmSamplingForm.fullDocNo"
          />
        </u-form-item> -->
        <u-form-item label="立案编号" :label-position="labelPosition">
          <u-input :disabled="!state.canEdit" v-model="zmSamplingForm.regNo" />
        </u-form-item>
        <u-form-item label="当事人" :label-width="labelWidth" :required="isRequired" prop="partyName">
          <u-input
            placeholder="请输入当事人"
            input-align="right"
            :disabled="!state.canEdit"
            v-model="zmSamplingForm.partyName"
          />
        </u-form-item>
        <u-form-item
          label="抽样依据"
          :label-position="labelPosition"
          :required="isRequired"
          prop="legal"
        >
          <u-input
            type="textarea"
            height="80"
            :auto-height="true"
            placeholder="请输入抽样依据"
            :disabled="true"
            v-model="zmSamplingForm.legal"
          />
        </u-form-item>
        <u-form-item label="抽样时间" :required="isRequired" prop="samplingTime" right-icon="arrow-right" :label-position="labelPosition" ref="changeRefS">
          <u-input placeholder="请输入抽样时间" :disabled="true" :clearable="false" v-model="zmSamplingForm.samplingTime" @click="()=>{if(state.canEdit) isShowRegDate = true}" />
        </u-form-item>
        <u-form-item label="抽样地点" :required="isRequired" prop="preSamplingPlace" :label-position="labelPosition">
          <u-input placeholder="请输入抽样地点" :disabled="!state.canEdit" v-model="zmSamplingForm.preSamplingPlace" />
        </u-form-item>
        <u-form-item prop="undertaker">
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-required">
                *
              </view>
              <view class="doc-sub-title">
                抽样人
              </view>
              <view
                class="uicon-sty"
                :style="isCanClick?'pointer-events: none;':''"
                @click="()=>{if(state.canEdit) personSelectShow = true}"
              >
                <u-icon name="plus-circle" color="#2979ff" size="40"></u-icon>
              </view>
            </view>
            <u-input
              type="textarea"
              height="100"
              :auto-height="true"
              placeholder="请输入"
              :disabled="true"
              v-model="zmSamplingForm.undertaker"
            />
          </view>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="备注">
          <u-input
            type="textarea"
            :maxlength="maxLength"
            :disabled="!state.canEdit"
            v-model="zmSamplingForm.remark"
          />
        </u-form-item>
        <view style="margin: -6px -16px 0px -16px;">
          <u-gap :height="$theme.cm_gap_height" :bg-color="$theme.cm_gap_color"></u-gap>
        </view>
        <view style="width: calc(100% + 30px);">
          <form-section title="抽样物品清单" iconColorClass="u-success">
          </form-section>
        </view>
        <view style="color: red;">
          (注：点击“样品名称”查看详情可删除记录)
        </view>
        <u-form-item :border-bottom="false">
          <view class="m-flex-row" style="width: 100%;">
            <view class="u-font-28 total-tip">
              合计(样品基数)<text>
                {{ totalBaseQty }}
              </text>条
            </view>
            <view class="u-font-28 total-tip">
              合计(样品数量)<text>
                {{ totalSampleQty }}
              </text>条
            </view>
          </view>
        </u-form-item>
        <u-form-item :label-position="labelPosition">
          <view class="u-p-b-20" style="width: 100%;" v-show="goodsListShow">
            <u-table font-size="26">
              <u-tr class="u-tr">
                <u-th class="u-th" width="25%">
                  样品名称
                </u-th>
                <u-th class="u-th" width="30%">
                  样品状态
                </u-th>
                <u-th class="u-th">
                  基数(条)
                </u-th>
                <u-th class="u-th">
                  数量(条)
                </u-th>
                <u-th class="u-th" width="10%">
                  单位
                </u-th>
              </u-tr>
              <u-tr class="u-tr" v-for="item in zmSamplingForm.goods" :key="item.goodsUuid">
                <u-td class="u-td" style="color: #2979ff;" width="25%">
                  <text @click="itemDetail(item)">
                    {{ item.goodsName }}
                  </text>
                </u-td>
                <u-td class="u-td" width="30%">
                  <view>
                    <dic-input
                      :keyWord="$u.dic.DIC_KEYS.Q_SAMPLE_DESCRIBE"
                      :dicCode="item.sampleType"
                      :border="true"
                      type="select"
                      :select-open="dicSelectOpen($u.dic.DIC_KEYS.Q_SAMPLE_DESCRIBE)"
                      placeholder="请选择"
                      :disabled="!state.canEdit"
                      v-model="item.getSampleTypeName"
                      @changeInputModelData="(name)=>{$set(item, 'getSampleTypeName', name)}"
                      @click="showDic($u.dic.DIC_KEYS.Q_SAMPLE_DESCRIBE,item.sampleType,item)"
                    />
                  </view>
                </u-td>
                <u-td class="u-td">
                  {{ item.baseQty }}
                </u-td>
                <u-td class="u-td">
                  <view>
                    <u-input type="text" :disabled="!state.canEdit" :border="true" placeholder="" v-model="item.sampleQty" @blur="onModifySampleQty(item)" />
                  </view>
                </u-td>
                <u-td class="u-td" width="10%">
                  {{ item.unit }}
                </u-td>
              </u-tr>
            </u-table>
          </view>
        </u-form-item>
      </u-form>
    </view>

<!-- 底部按钮开始 -->
<!-- <view class="bottom-btn-info" v-if="state.canEdit"> -->
<!-- <u-row gutter="16"> -->
<!-- <u-col span="6"> -->
<!-- <u-button plain type="primary" @click="submitBtn('save')"> -->
<!-- 保存 -->
<!-- </u-button> -->
<!-- </u-col> -->
<!-- <u-col span="6"> -->
<!-- <u-button type="primary" @click="submitBtn('submit')"> -->
<!-- 提交 -->
<!-- </u-button> -->
<!-- </u-col> -->
<!-- </u-row> -->
<!-- </view> -->
<view class="submit-btns btn-other-cls" v-if="state.canEdit">
	<u-button plain class="u-btn" type="primary" @click="submitBtn('save')">
		保存
	</u-button>
	<u-button class="u-btn" type="primary" @click="submitBtn('submit')">
		提交
	</u-button>
</view>
    <!-- 底部按钮结束 -->
    <!-- 人员选择 -->
    <u-popup mode="bottom" height="80%" v-model="personSelectShow">
      <person-selection :params="psParam" @choose="handlerChoosePerson"></person-selection>
    </u-popup>
    <u-picker mode="time" :params="paramsDate" v-model="isShowRegDate" @confirm="confirmDate"></u-picker>
    <dic-choice
      :keyWord="dicKeyWords"
      :currentSelect="dicCurrentSelect"
      v-model="dicShow"
      @confirm="selectDicConfirm"
    ></dic-choice>
    <!-- 抽样物品详情 -->
    <u-popup mode="bottom" height="32%" v-model="detailShow">
      <view class="content" style="padding: 40rpx;">
        <view style="position: fixed;top: 0;width: 100%;height: 30rpx;background-color: white;"></view>
        <view style="padding-bottom: 120rpx;">
          <u-row gutter="16">
            <u-col span="12">
              <text style="font-size: 30rpx;">
                品牌品规: {{ detailData.goodsName }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                条条形码: {{ detailData.stripCode }}
              </text>
            </u-col>
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                盒条形码: {{ detailData.packCode }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                样品基数（条）: {{ detailData.baseQty }}
              </text>
            </u-col>
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                样品数量（条）: {{ detailData.sampleQty }}
              </text>
            </u-col>
          </u-row>
          <u-row gutter="16">
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                样品状态: {{ getDicName($u.dic.DIC_KEYS.Q_SAMPLE_DESCRIBE, detailData.sampleType) }}
              </text>
            </u-col>
            <u-col span="6">
              <text style="font-size: 24rpx;color: #666666;">
                单位: {{ detailData.unit }}
              </text>
            </u-col>
          </u-row>
        </view>
        <view
          class="nwidth"
          style="padding: 10rpx;bottom: 20rpx;position: fixed;background-color: white;"
          v-if="state.canEdit"
        >
          <u-button size="default" type="error" plain @click="delGoodsItem">
            删除记录
          </u-button>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
	import caseCommon from "../caseCommonMixin.js";
	import officeService from "@/service/case/office.service.js";
	import PersonSelection from "@/pages/case/components/personSelection.vue";
	import {
		dateUtils,
	} from "@/common/util";
	import DocFormContentTep from "../components/docFormContentTemplate.vue";
	import zjCommonService from "@/service/common/common.service";
	import FormSection from "@/components/form-section.vue";
	import DicChoice from "@/components/dic_choice.vue";
	import DicInput from "@/components/dic_input.vue";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			PersonSelection,
			FormSection,
			"dic-choice": DicChoice,
			"dic-input": DicInput,
			fabButton
		},
		mixins: [caseCommon, ],
		data() {
			return {
				paramsDate: {
					year: true,
					month: true,
					day: true,
					hour: true,
					minute: true,
					second: true,
					timestamp: true,
				},
				yestDate: this.$u.timeFormat(Date.now()),
				isShowRegDate: false,
				errorType: ['border-bottom', 'message', ],
				isRequired: true,
				labelWidth: '220',
				labelPosition: 'top',
				maxLength: 9999,
				isCanClick: false, // 是否可点击承办人按钮
				employeeLst: [], // 选择人员数据
				caseParam: {}, // 上个页面传过来的参数
				zmSamplingForm: {},
				currGoods: {},
				doc: {},
				personSelectShow: false,
				psParam: {
					min: 2,
				},
				rules: {
					partyName: [{
						required: true,
						message: '请输入当事人',
						trigger: ['change', 'blur', ],
					}, ],
					samplingTime: [{
						required: true,
						message: '请选择抽样时间',
						trigger: ['change', 'blur', ],
					}, ],
					preSamplingPlace: [{
						required: true,
						message: '请输入抽样地点',
						trigger: ['change', 'blur', ],
					}, ],
					undertaker: [{
						required: true,
						message: '请选择抽样人',
						trigger: ['change', 'blur', ],
					}, ],
				},
				goodsListShow: true,
				titSty: {
					'font-size': '32rpx',
					'padding-left': '0rpx',
				},
				btnType: "",
				dicShow: false, // dic_select 是否显示
				dicKeyWords: "", // dic 关键字
				dicCurrentSelect: "", // dic 当前选择项
				detailShow: false,
				detailData: {},
				fContent: [{
					iconPath: require('@/static/oview.png'),
					selectedIconPath: require('@/static/oview.png'),
					text: '预览',
					active: false,
				}],
				fContents: [{
					iconPath: require('@/static/dy.png'),
					selectedIconPath: require('@/static/dy.png'),
					text: '打印',
					active: false,
				}]
			}
		},
		computed: {
			arrow() {
				return this.goodsListShow ? "down" : "right";
			},
			// 样品基数合计
			totalBaseQty() {
				let total_qty = 0;
				if (this.zmSamplingForm.goods) {
					this.zmSamplingForm.goods.forEach((item) => {
						total_qty += Number(item.baseQty);
					});
				}
				return total_qty;
			},
			// 样品数量合计
			totalSampleQty() {
				let total_sam_qty = 0;
				if (this.zmSamplingForm.goods) {
					this.zmSamplingForm.goods.forEach((item) => {
						let qty = item.sampleQty ? item.sampleQty : '0';
						total_sam_qty += Number(qty);
					});
				}
				return total_sam_qty;
			},
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		watch: {
			isShowRegDate() {
				this.$refs.changeRefS.validation();
			},
		},
		onLoad(preParams) {
			this.caseParam = this.getRouteParam();
			this.psParam.caseUuid = this.caseParam.caseUuid;
		},
		mounted() {
			this.docStep((docInfo) => {
				this.doc = docInfo;
				this.setRightBtns();
			});
			this.initDocData();
		},
		methods: {
			initDocData() {
				let parms = {
					id: this.caseParam.id,
					docUuid: this.caseParam.docUuid,
					bizUuid: this.caseParam.bizUuid,
				}
				officeService.docFields(this.caseParam.docUuid, true).then(docConfigs => {
					if (docConfigs.success) {
						this.docFields = [...docConfigs.data, ];
						this.$modal.showLoading('加载中');
						// 获取数据
						officeService.getDocZmSampling(parms).then((res) => {
							this.$modal.hideLoading();
							let [tiInfo, rs, ] = [{}, {}, ];
							if (res.success && res.data.length === 2) {
								tiInfo = res.data[0];
								rs = res.data[1];
								Object.keys(tiInfo).forEach(key => {
									rs[key] = tiInfo[key];
								});
							} else {
								rs = res.data[0];
							}
							this.zmSamplingForm = rs;
							this.zmSamplingForm.fullDocNo = this.zmSamplingForm.fullDocNo ? this.zmSamplingForm.fullDocNo : this.zmSamplingForm.orgAbbr + '抽样〔〕号';
							this.zmSamplingForm.legal = this.zmSamplingForm.legal ? this.zmSamplingForm.legal : '国烟科〔2014〕285号《烟草专卖品鉴别检验管理办法》  国烟科〔2006〕894号《卷烟产品鉴别检验规程》';
							console.log('======', this.zmSamplingForm)
						});
					} else {
						this.$u.toast(docConfigs.msg);
					}
				});
			},

			// 设置右侧标题
			setRightBtns() {
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight(this.state.canEdit ? '预览' : '打印', () => {
					this.printOrDown(this.state.canEdit);
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.printOrDown(this.state.canEdit);
				}
			},
			// 打印/预览
			printOrDown(flag) {
				if (flag) {
					// 调接口预览
					this.submitDocInfo('preview');
				} else {
					this.downloadFile(this.doc.pdfFileId);
				}
			},
			downloadFile(fileId, titleName, isDownload) {
				let pdfIds = fileId;
				if (!pdfIds) {
					this.$u.toast("没有文书");
					return;
				}
				this.setRouteParam({
					fileId: pdfIds,
					fileName: titleName,
					isDownload: isDownload,
				});
				this.$u.route('pages/commonPage/printerComponent');
			},
			confirmDate(e) {
				this.zmSamplingForm.samplingTime = this.$u.date(e.timestamp, 'yyyy年mm月dd日 hh时MM分')
			},
			// 选择执行人
			handlerChoosePerson(e) {
				this.personSelectShow = false;
				this.employeeLst = [...e, ];
				let tIds = [];
				let tNames = [];
				this.employeeLst.forEach(el => {
					tIds.push(el.personUuid);
					tNames.push(el.personName + "(" + el.leCertNo + ")");
				});
				this.zmSamplingForm['undertakerUuids'] = tIds.join(",");
				this.zmSamplingForm['undertaker'] = tNames.join(",");
			},
			dicSelectOpen: function(keyWords) {
				if (this.dicKeyWords == keyWords && this.dicShow) {
					return true;
				}
				return false;
			},
			showDic: function(key, cur, item) {
				if (!this.state.canEdit) return;
				if (this.dicShow) return;
				this.dicKeyWords = key;
				this.dicCurrentSelect = cur;
				this.dicShow = true;
				this.currGoods = item;
			},
			selectDicConfirm: function(e) {
				// 样品状态
				if (this.dicKeyWords == this.$u.dic.DIC_KEYS.Q_SAMPLE_DESCRIBE) {
					this.zmSamplingForm.goods.forEach((item, index) => {
						if (item.goodsUuid == this.currGoods.goodsUuid) {
							item.getSampleTypeName = e[0].label;
							item.sampleType = e[0].extra.bcbCode;
						}
					});
				}
			},
			/**
			 * 样品数量 输入数量处理
			 * @param goods
			 */
			onModifySampleQty(goods) {
				let reg = new RegExp('^\\d+(\\.\\d+)?$');
				if (goods.sampleQty != '') {
					// 验证输入的抽样数量是否正确
					if (!reg.test(String(goods.sampleQty))) {
						this.showToast("请输入数字！");
						goods.sampleQty = '0';
					} else {
						if (Number(goods.sampleQty) > 999999) {
							this.showToast("超出最大样品数量!");
							goods.sampleQty = '0';
							return;
						}
						let jy = new Intl.NumberFormat(["cn-ZH", ], {
							style: "decimal",
							maximumFractionDigits: 2,
						});
						let temp = jy.format(Number(goods.sampleQty));
						temp = temp.replace(/,/g, "");
						goods.sampleQty = temp;
					}
				} else {
					goods.sampleQty = '0';
				}
			},
			itemDetail(obj) {
				this.detailData = obj;
				this.detailShow = true;
			},
			getDicName(keyword, code) {
				return this.$u.dic.getDicNameByKeyCode(keyword, code);
			},
			// 删除
			delGoodsItem() {
				this.detailShow = false;
				this.$modal.confirm("确定要删除此记录吗？", () => {
					let idx = '';
					this.zmSamplingForm.goods.forEach((itm, index) => {
						if (itm.goodsUuid == this.detailData.goodsUuid) {
							idx = index;
							return;
						}
					});
					this.zmSamplingForm.goods.splice(idx, 1);
					console.log(this.zmSamplingForm.goods);
				});
			},
			// 表单验证
			validForm(type) {
				let basicValid = false;
				this.btnType = type;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						basicValid = true;
						console.log('表单验证通过');
					} else {
						basicValid = false;
						console.log('表单验证失败');
					}
				});
				return basicValid;
			},
			// 验证物品信息
			validGoods() {
				let flag = true;
				this.zmSamplingForm.goods.forEach((item) => {
					if (!item.sampleType) {
						this.$u.toast("请选择样品状态");
						flag = false;
						return false;
					}
					if (!item.sampleQty || item.sampleQty == '0' || item.sampleQty == 0) {
						this.$u.toast("请输入样品数量");
						flag = false;
						return false;
					}
				});
				return flag;
			},
			submitBtn(type) {
				// 点击提交、保存按钮
				let flag = this.validForm(type);
				let goodFlag = this.validGoods();
				if (flag && goodFlag) {
					if (this.zmSamplingForm.goods.length > 0) {
						if (type == 'submit') {
							this.$modal.confirm("完成后不可修改，请确认是否填写完整准确无误？", () => {
								this.submitDocInfo(type);
							});
						} else {
							this.submitDocInfo(type);
						}
					} else {
						this.$modal.alert("无抽样物品，或抽样数量为空！");
					}
				}
			},
			// 保存/提交接口
			submitDocInfo(type) {
				let {
					id,
					docUuid,
					titemUuid,
				} = this.caseParam;
				type == 'save' && this.$u.loading('数据保存中...');
				officeService.saveDocZmSampling(this.zmSamplingForm, docUuid, titemUuid, id, this.caseParam.type).then(
					res => {
						this.$u.hideLoading();
						if (res.success) {
							this.zmSamplingForm = res.bean;
							try {
								if (!this.doc) this.doc = res.data[0];
							} catch (e) {
								console.log(e);
							}
							if (type == 'submit') {
								this.$u.loading('数据提交中...');
								officeService.submitDocZmSampling(this.zmSamplingForm, docUuid, titemUuid, id, this
									.caseParam.type).then(res => {
									this.$u.hideLoading();
									this.saveBehaviorLog(1, this.caseParam, this.doc);
									this.$u.toast(res.msg);
									if (res.success) {
										this.backPrev({
											paramKey: "offiList",
											param: {
												caseUuid: this.caseParam.bizUuid,
											},
										});
									}
								})
							} else if (type == 'preview') {
								officeService.buildLocalPunish("/price/doc-zm-sampling", this.doc.docInsUuid).then(
									pdfId => {
										if (pdfId.success) {
											this.downloadFile(pdfId.bean, "预览", false);
										} else {
											this.$u.toast(pdfId.msg);
										}
									});
							} else {
								this.saveBehaviorLog(0, this.caseParam, this.doc);
								this.$u.toast(res.msg);
							}
						} else {
							this.$u.hideLoading();
							this.$u.toast(res.msg);
						}
					})
			},
		},
	}
</script>
<style lang="scss" scoped>
	@import "../case_common.scss";

	.page {
		padding: 0px;
	}

	/deep/ .main-content .u-cell {
		padding-left: 0px;
	}

	.u-td {
		white-space: nowrap;
		overflow: hidden;
		height: auto;
		line-height: 20px;
	}

	.total-tip {
		color: $u-tips-color;

		text {
			color: $u-type-warning;
			margin-left: 10rpx;
			margin-right: 10rpx;
		}
	}

	.nwidth {
		width: calc(100% - 80rpx);
	}

	/deep/ .u-row {
		line-height: 35px;
	}
</style>
